#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdint.h>
#include <signal.h>

#include "tinyalsa/asoundlib.h"

#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT  0x20746d66
#define ID_DATA 0x61746164

struct riff_wave_header {
    uint32_t riff_id;
    uint32_t riff_sz;
    uint32_t wave_id;
};

struct chunk_header {
    uint32_t id;
    uint32_t sz;
};

struct chunk_fmt {
    uint16_t audio_format;
    uint16_t num_channels;
    uint32_t sample_rate;
    uint32_t byte_rate;
    uint16_t block_align;
    uint16_t bits_per_sample;
};

static int close = 0;

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count);

static int tinymixer_set_value(const int control, int *values, unsigned int num_values);

void stream_close(int sig)
{
    /* allow the stream to be closed gracefully */
    signal(sig, SIG_IGN);
    close = 1;
}

static long int file_size(FILE * file)
{
    if (fseek(file, 0, SEEK_END) < 0) {
        return -1;
    }
    long int file_size = ftell(file);
    if (fseek(file, 0, SEEK_SET) < 0) {
        return -1;
    }
    return file_size;
}

int tinyalsa_play(const char* file_name)
{
    FILE *file;
    struct riff_wave_header riff_wave_header;
    struct chunk_header chunk_header;
    struct chunk_fmt chunk_fmt;
    unsigned int device = 0;
    unsigned int card = 0;
    unsigned int period_size = 1024;
    unsigned int period_count = 16;
    char *filename;
    int more_chunks = 1;
    struct mixer *mixer;
    fpos_t pos;

    int values[2] = {0};

    values[0] = 50;
    values[1] = 50;
    tinymixer_set_value(0, values, 2);

    file = fopen(file_name, "rb");
    if (!file) {
        fprintf(stderr, "Unable to open file '%s'\n", "1.wav");
        return 1;
    }

    printf("1.The file pointer is at byte %ld\n", ftell(file));

    fread(&riff_wave_header, sizeof(riff_wave_header), 1, file);
    if ((riff_wave_header.riff_id != ID_RIFF) ||
        (riff_wave_header.wave_id != ID_WAVE)) {
        fprintf(stderr, "Error: '%s' is not a riff/wave file\n", filename);
        fclose(file);
        return 1;
    }

    printf("2.The file pointer is at byte %ld\n", ftell(file));

    do {
        fread(&chunk_header, sizeof(chunk_header), 1, file);

        switch (chunk_header.id) {
        case ID_FMT:
            fread(&chunk_fmt, sizeof(chunk_fmt), 1, file);
            printf("seek ID_FMT\r\n");
            /* If the format header is larger, skip the rest */
            if (chunk_header.sz > sizeof(chunk_fmt))
                fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR);
            break;
        case ID_DATA:
            /* Stop looking for chunks */
            more_chunks = 0;
            printf("seek ID_DATA\r\n");
            break;
        default:
            /* Unknown chunk, skip bytes */
            fseek(file, chunk_header.sz, SEEK_CUR);
            printf("seek default\r\n");
        }
    } while (more_chunks);

    printf("3.The file pointer is at byte %ld\n", ftell(file));

    printf("riff_wave_header=%d, chunk_header=%d, chunk_fmt=%d\r\n", sizeof(riff_wave_header), sizeof(chunk_header), sizeof(chunk_fmt));

    play_sample(file, card, device, chunk_fmt.num_channels, chunk_fmt.sample_rate,
                chunk_fmt.bits_per_sample, period_size, 16);

    fclose(file);

    return 0;
}

int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
                 char *param_name, char *param_unit)
{
    unsigned int min;
    unsigned int max;
    int is_within_bounds = 1;

    min = pcm_params_get_min(params, param);
    if (value < min) {
        fprintf(stderr, "%s is %u%s, device only supports >= %u%s\n", param_name, value,
                param_unit, min, param_unit);
        is_within_bounds = 0;
    }

    max = pcm_params_get_max(params, param);
    if (value > max) {
        fprintf(stderr, "%s is %u%s, device only supports <= %u%s\n", param_name, value,
                param_unit, max, param_unit);
        is_within_bounds = 0;
    }

    return is_within_bounds;
}

int sample_is_playable(unsigned int card, unsigned int device, unsigned int channels,
                        unsigned int rate, unsigned int bits, unsigned int period_size,
                        unsigned int period_count)
{
    struct pcm_params *params;
    int can_play;

    params = pcm_params_get(card, device, PCM_OUT);
    if (params == NULL) {
        fprintf(stderr, "Unable to open PCM device %u.\n", device);
        return 0;
    }

    can_play = check_param(params, PCM_PARAM_RATE, rate, "Sample rate", "Hz");
    can_play &= check_param(params, PCM_PARAM_CHANNELS, channels, "Sample", " channels");
    can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, bits, "Bitrate", " bits");
    can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, period_size, "Period size", "Hz");
    can_play &= check_param(params, PCM_PARAM_PERIODS, period_count, "Period count", "Hz");

    pcm_params_free(params);

    return can_play;
}

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count)
{
    struct pcm_config config;
    struct pcm *pcm;
    char *buffer;
    int size;
    int num_read;

    config.channels = channels;
    config.rate = rate;
    config.period_size = period_size;
    config.period_count = period_count;
    if (bits == 32)
        config.format = PCM_FORMAT_S32_LE;
    else if (bits == 16)
        config.format = PCM_FORMAT_S16_LE;
    config.start_threshold = 0;
    config.stop_threshold = 0;
    config.silence_threshold = 0;

    if (!sample_is_playable(card, device, channels, rate, bits, period_size, period_count)) {
        return;
    }

    pcm = pcm_open(card, device, PCM_OUT, &config);
    if (!pcm || !pcm_is_ready(pcm)) {
        fprintf(stderr, "Unable to open PCM device %u (%s)\n",
                device, pcm_get_error(pcm));
        return;
    }

    size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
    printf("pcm size=%d\r\n", size);
    buffer = malloc(size);
    if (!buffer) {
        fprintf(stderr, "Unable to allocate %d bytes\n", size);
        free(buffer);
        pcm_close(pcm);
        return;
    }

    printf("Playing sample: %u ch, %u hz, %u bit\n", channels, rate, bits);

    /* catch ctrl-c to shutdown cleanly */
    signal(SIGINT, stream_close);

    printf("4.The file pointer is at byte %ld\n", ftell(file));

    do {
        num_read = fread(buffer, 1, size, file);
        if (num_read > 0) {
            if (pcm_write(pcm, buffer, num_read)) {
                printf("Error playing sample\n");
                break;
            }
        }
    } while (!close && num_read > 0);

    printf("ctrl-c\r\n");
    free(buffer);
    pcm_close(pcm);
    printf("clean\r\n");
}

struct pcm* pcm_dev_init(int rate)
{
    unsigned int card = 0;
    unsigned int device = 0;
    int flags = PCM_OUT;
//    int values[2] = {0};
    int size;

//    values[0] = 60;
//    values[1] = 60;
//    tinymixer_set_value(0, values, 2);

    set_vol(30, 30);

    const struct pcm_config config = {
        .channels = 2,
        .rate = rate,
        .format = PCM_FORMAT_S16_LE,
        .period_size = 64,
        .period_count = 16,
        .start_threshold = 512,
        .silence_threshold = 0,
        .stop_threshold = 0
    };



    struct pcm* pcm = pcm_open(card, device, flags, &config);
    if (pcm == NULL) {
        fprintf(stderr, "failed to allocate memory for PCM\n");
        return -1;
    } else if (!pcm_is_ready(pcm)){
        pcm_close(pcm);
        fprintf(stderr, "failed to open PCM\n");
//        return -1;
    }

    size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
    printf("pcm size=%d\r\n", size);

    return pcm;
}

struct pcm* pcm_cap_dev_init(int rate)
{
    unsigned int card = 0;
    unsigned int device = 0;
    int flags = PCM_IN;
//    int values[2] = {0};
    int size;

//    values[0] = 60;
//    values[1] = 60;
//    tinymixer_set_value(0, values, 2);

    set_cap_vol(30, 30); //录音音频增益
    capture_open();

    const struct pcm_config config = {
        .channels = 2,
        .rate = rate,
        .format = PCM_FORMAT_S16_LE,
        .period_size = 64,
        .period_count = 64,
        .start_threshold = 0,
        .silence_threshold = 0,
        .stop_threshold = 0
    };

    struct pcm* pcm = pcm_open(card, device, flags, &config);
    if (pcm == NULL) {
        fprintf(stderr, "failed to allocate memory for PCM\n");
        return pcm;
    } else if (!pcm_is_ready(pcm)){
        pcm_close(pcm);
        fprintf(stderr, "failed to open PCM\n");
        pcm = NULL;
        return pcm;
    }

    size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
    printf("pcm size=%d\r\n", size);

    return pcm;
}

int pcm_dev_close(struct pcm * pcm)
{
    pcm_close(pcm);
}

int pcm_cap_dev_close(struct pcm * pcm)
{
    capture_close();
    pcm_close(pcm);
}

int pcm_dev_write(struct pcm * pcm, const void * frames, size_t byte_count)
{
    unsigned int frame_count = pcm_bytes_to_frames(pcm, byte_count);
//    printf("frame_cout = %d, byte_count=%d \r\n", frame_count, byte_count);

    return pcm_write(pcm, frames, byte_count);
}

int pcm_dev_read(struct pcm * pcm, void * buffer, size_t byte_count)
{
    unsigned int frame_count = pcm_bytes_to_frames(pcm, byte_count);
//    printf("frame_cout = %d, byte_count=%d \r\n", frame_count, byte_count);

    if(!pcm_read(pcm, buffer, byte_count))
        return frame_count;
    else
        return -1;
}



int write_frames(const void * frames, size_t byte_count){

    unsigned int card = 0;
    unsigned int device = 0;
    int flags = PCM_OUT;

    const struct pcm_config config = {
        .channels = 2,
        .rate = 48000,
        .format = PCM_FORMAT_S16_LE,
        .period_size = 1024,
        .period_count = 16,
        .start_threshold = 1024,
        .silence_threshold = 1024 * 2,
        .stop_threshold = 1024 * 2
    };

    struct pcm * pcm = pcm_open(card, device, flags, &config);
    if (pcm == NULL) {
        fprintf(stderr, "failed to allocate memory for PCM\n");
        return -1;
    } else if (!pcm_is_ready(pcm)){
        pcm_close(pcm);
        fprintf(stderr, "failed to open PCM\n");
        return -1;
    }

    unsigned int frame_count = pcm_bytes_to_frames(pcm, byte_count);

    pcm_write(pcm, frames, frame_count);

    pcm_close(pcm);

    return 0;
}

static void tinymix_set_value(struct mixer *mixer, const int control,
                              int *values, unsigned int num_values)
{
    struct mixer_ctl *ctl;
    enum mixer_ctl_type type;
    unsigned int num_ctl_values;
    unsigned int i;

    ctl = mixer_get_ctl(mixer, control);

    if (!ctl) {
        fprintf(stderr, "Invalid mixer control\n");
        return;
    }

    type = mixer_ctl_get_type(ctl);
    num_ctl_values = mixer_ctl_get_num_values(ctl);

    if (num_values == 1)
    {
        /* Set all values the same */
        int value = values[0];

        for (i = 0; i < num_ctl_values; i++)
        {
            if (mixer_ctl_set_value(ctl, i, value))
            {
                fprintf(stderr, "Error: invalid value\n");
                return;
            }
        }
    }
    else
    {
        /* Set multiple values */
        if (num_values > num_ctl_values)
        {
            fprintf(stderr,
                    "Error: %d values given, but control only takes %d\n",
                    num_values, num_ctl_values);
            return;
        }
        for (i = 0; i < num_values; i++)
        {
            if (mixer_ctl_set_value(ctl, i, values[i]))
            {
                fprintf(stderr, "Error: invalid value for index %d\n", i);
                return;
            }
        }
    }
}

static int tinymixer_set_value(const int control, int *values, unsigned int num_values)
{
    struct mixer *mixer;
    unsigned int card = 0;

    mixer = mixer_open(card);
    if (!mixer) {
        fprintf(stderr, "Failed to open mixer\n");
        return EXIT_FAILURE;
    }

    tinymix_set_value(mixer, control, values, num_values);

    mixer_close(mixer);
}

void set_vol(int left, int right)
{
    int values[2];

    values[0] = left;
    values[1] = right;
    tinymixer_set_value(0, values, 2);
}

void set_cap_vol(int left, int right)
{
    int values[2];

    values[0] = left;
    values[1] = right;
    tinymixer_set_value(36, values, 2);
}

void capture_open()
{
    int values[2] = {1, 1};

    tinymixer_set_value(37, values, 2);
}

void capture_close()
{
    int values[2] = {0, 0};

    tinymixer_set_value(37, values, 2);
}

